package com.wutong.resonance.model.audio.tool;

import com.wutong.resonance.model.audio.enums.AudioType;
import com.wutong.resonance.model.exception.AudioException;
import com.wutong.resonance.model.util.FileUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.URI;

import static com.wutong.resonance.model.util.FileUtil.getSuffix;

/**
 * 音频文件封装类
 * @author wutong
 */
@Slf4j
@Getter
public class AudioFile extends File {

    private final AudioType audioType;
    private AudioFile tmpFile;

    public AudioFile(String pathname, AudioType audioType) {
        super(pathname);
        this.audioType = audioType;
    }

    public AudioFile(URI uri, AudioType audioType) {
        super(uri);
        this.audioType = audioType;
    }

    public AudioFile(File file, AudioType audioType) {
        super(file.getAbsolutePath());
        if (getSuffix(file).equals(audioType.getType())) {
            this.audioType = audioType;
        } else {
            log.error("文件类型不匹配，请检查文件类型是否为：{}", audioType.getType());
            throw new AudioException.AudioFileLoadException("文件类型不匹配，请检查文件类型是否为：" + audioType.getType());
        }
    }

    public AudioFile createTempFile() {
        if (this.tmpFile == null) {
            this.tmpFile = new AudioFile(FileUtil.createTempFile(this), audioType);
        }
        return this.tmpFile;
    }

    public void deleteTempFile() {
        if (this.tmpFile!= null) {
            if (this.tmpFile.delete()) {
                log.info("临时文件{}已删除", this.tmpFile.getAbsolutePath());
            } else {
                log.warn("临时文件{}删除失败", this.tmpFile.getAbsolutePath());
            }
            this.tmpFile = null;
        }
    }
}
